package com.neteast.androidclient.contact.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.Test;
import com.neteast.androidclient.contact.adapter.SearchResultAdapter;
import com.neteast.androidclient.contact.adapter.SimpleStrAdapter;
import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.domain.ContactRowManager;
import com.neteast.androidclient.contact.widget.ContactPanel;
import com.neteast.androidclient.contact.widget.ContactBgPanel;
import com.neteast.androidclient.contact.widget.GroupPanel;
import com.neteast.androidclient.contact.widget.InfoDetailPanel;

/**
 * 显示所有联系人信息的页面
 * 
 * @author yangxun 2012-3-13 下午1:33:04
 */
public class ContactActivity extends Activity implements OnClickListener {
	private String TAG = "ContactActivity";
	private Button tab1, tab2;// 云好友和通讯录好友切换标签
	private ImageView btnMore;
	private LinearLayout contactView;// 视图容器
	private RelativeLayout tab1View;
	private RelativeLayout tab2View;
	private int currentView; // 判断当前在哪个标签页上，1是云好友，2是通讯好友
	private PopupWindow morePopupWindow;
	private LinearLayout morePopupView;
	private View groupPopupView;
	private PopupWindow groupPopupWindow;
	private View searchPopupView;
	private PopupWindow searchPopupWindow;
	private LayoutInflater mInflater;
	private InfoDetailPanel infoDetail;
//	private LinearLayout createNewLayout;// 新建联系人布局
	private ListView groupList;// 分组列表
	private GroupPanel groupPanel;//左边拉动视图

	private WindowManager windowManager;
	private List<ResolveInfo> mList;
	private PackageManager mPackageManager;
	private final int DLG_DELETE_GROUP_HEIGHT = 178;
	private final int DLG_DELETE_GROUP_WIDTH = 376;
	private final int DLG_EDIT_GROUP_HEIGHT = 248;
	private final int DLG_EDIT_GROUP_WIDTH = 504;
	private ArrayList<String> searchIndexs;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		findView();
		init();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void findView() {
		tab1 = (Button) findViewById(R.id.Tab1);
		tab2 = (Button) findViewById(R.id.Tab2);
		btnMore = (ImageView) findViewById(R.id.btnMore);
		contactView = (LinearLayout) findViewById(R.id.contactView);
		tab1.setOnClickListener(this);
		tab2.setOnClickListener(this);
		btnMore.setOnClickListener(this);
		tab1View = (RelativeLayout) getLayoutInflater().inflate(
				R.layout.contact_view, null);
		tab2View = (RelativeLayout) getLayoutInflater().inflate(
				R.layout.contact_view, null);
		
		groupList = (ListView) findViewById(R.id.groupList);
		groupPanel = (GroupPanel) findViewById(R.id.leftPanel);
	}

	private void init() {
		mContext = ContactActivity.this;
		mInflater = LayoutInflater.from(mContext);
		//创建弹窗对象
		morePopupView = (LinearLayout) getLayoutInflater()
				.inflate(R.layout.popup_view, null);
		morePopupWindow = new PopupWindow(morePopupView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				false);
		groupPopupView = mInflater.inflate(R.layout.group_manager_view, null);
		groupPopupWindow = new PopupWindow(groupPopupView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				false);
		searchPopupView = mInflater.inflate(R.layout.search, null);
		searchPopupWindow = new PopupWindow(searchPopupView,
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
				false);
		searchPopupWindow.setFocusable(true);
		infoDetail = new InfoDetailPanel(mContext, Test.getContact());
		searchIndexs = new ArrayList<String>();
		String[] tmp = getResources().getStringArray(R.array.search_index_arrays);
		for(int i = 0; i<tmp.length; i++){
			searchIndexs.add(tmp[i]);
		}
		ArrayList<String> groupArray = new ArrayList<String>();
		for(int i = 0; i<5; i++){
			groupArray.add("分组"+i);
		}
		loadCloudFriends();
		switchView(1);
		loadGroupList(groupArray);

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.Tab1:
			loadCloudFriends();
			contactView.removeAllViews();
			contactView.addView(tab1View);
			switchView(1);
			break;
		case R.id.Tab2:
			loadCommFriends();
			contactView.removeAllViews();
			contactView.addView(tab2View);
			switchView(2);
			break;
		case R.id.btnMore:
			showPopupWindow(currentView);
			break;
		//下拉菜单项按钮
		case R.id.btnCreateNew:
			
			startActivity(new Intent(ContactActivity.this, NewContactActivity.class));
			morePopupWindow.dismiss();
			break;
		case R.id.btnImport:
			break;
		case R.id.btnManage:
			
			break;
		case R.id.btnFindFriends:
			break;
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			if (morePopupWindow.isShowing()) {
				morePopupWindow.dismiss();
				return false;
			}
			if(groupPopupWindow.isShowing()){
				groupPopupWindow.dismiss();
				return false;
			}
			break;
		}

		return super.dispatchTouchEvent(ev);
	}

	/**
	 * 根据选择的按钮变换背景
	 * */
	private void switchView(int tab) {
		if (tab == 1) {
			tab1.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_cloud_friends_selected));
			tab2.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_comm_friends_normal));
		} else if (tab == 2) {
			tab2.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_comm_friends_selected));
			tab1.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_cloud_friends_normal));
		}
	}

	/**
	 * 载入云好友通讯录
	 * */
	private void loadCloudFriends() {
		currentView = 1;
		ListView listView = (ListView) tab1View.findViewById(R.id.searchIndex);
		ImageView btnSearch = (ImageView) tab1View.findViewById(R.id.btnSearch);
		
		final SimpleStrAdapter adapter = new SimpleStrAdapter(
				ContactActivity.this, searchIndexs, R.layout.index_list_item);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {

				} else {
					Toast.makeText(mContext,
							adapter.getItem(position - 1).toString(),
							Toast.LENGTH_SHORT).show();
				}

			}
		});
		btnSearch.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
//				searchPopupWindow.showAsDropDown(tab1, 0, -10);
//				setSearchView();
				startActivity(new Intent(mContext, SearchActivity.class));
			}
		});

		// 添加名片GridView视图
		ContactBgPanel layout = new ContactBgPanel(mContext);
		LinearLayout contactGrid = (LinearLayout) tab1View
				.findViewById(R.id.contactGrid);
		;// 主要显示名片的布局
		mPackageManager = getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN, null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		mList = mPackageManager.queryIntentActivities(intent, 0);
		// 排序
		Collections.sort(mList, new ResolveInfo.DisplayNameComparator(
				mPackageManager));
		// 初始化
		ContactPanel panel = new ContactPanel(mContext, mPackageManager, mList, infoDetail);
		layout.addView(panel);
		LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		contactGrid.addView(layout, lp1);
		contactView.removeAllViews();
		contactView.addView(tab1View);
	}

	/**
	 * 载入通讯录画面 加载索引字母列表
	 * */
	private void loadCommFriends() {
		currentView = 2;
		ListView listView = (ListView) tab2View.findViewById(R.id.searchIndex);
		ImageView btnSearch = (ImageView) tab2View.findViewById(R.id.btnSearch);
		final SimpleStrAdapter adapter = new SimpleStrAdapter(
				ContactActivity.this, searchIndexs, R.layout.index_list_item);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(position == 0){
					
				}else{
					Toast.makeText(mContext, adapter.getItem(position - 1).toString(),
							Toast.LENGTH_SHORT).show();
				}

			}
		});
		btnSearch.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
//				searchPopupWindow.showAsDropDown(tab2, 0, -10);
//				setSearchView();
				
			}
		});

		// 添加名片GridView视图
		ContactBgPanel layout = new ContactBgPanel(mContext);
		LinearLayout contactGrid = (LinearLayout) tab2View
				.findViewById(R.id.contactGrid);
		;// 主要显示名片的布局
		mPackageManager = getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN, null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		mList = mPackageManager.queryIntentActivities(intent, 0);
		// 排序
		Collections.sort(mList, new ResolveInfo.DisplayNameComparator(
				mPackageManager));
		// 初始化
		ContactPanel panel = new ContactPanel(mContext, mPackageManager, mList, infoDetail);
		layout.addView(panel);
		LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		contactGrid.addView(layout, lp1);
		contactView.removeAllViews();
		contactView.addView(tab2View);

	}

	/**
	 * 创建新联系人的视图
	 * */
//	private void createNewContact() {
//		createNewLayout.setVisibility(View.INVISIBLE);
//		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
//				415, LayoutParams.MATCH_PARENT,
//				WindowManager.LayoutParams.TYPE_APPLICATION,
//				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
//				PixelFormat.TRANSLUCENT);
//		lp.gravity = Gravity.RIGHT;
//		windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
//		windowManager.addView(createNewLayout, lp);
//	}

	/**
	 * 设置分组列表视图
	 * */
	private void loadGroupList(ArrayList<String> array) {
		final SimpleStrAdapter adapter = new SimpleStrAdapter(
				ContactActivity.this, array, R.layout.group_list_item);
		final View dialogView = mInflater.inflate(R.layout.dlg_add_group, null);
		final Dialog dialog = new Dialog(mContext, R.style.DialogStyle);
		//弹出框内的组件
		final Button btnOk = (Button) dialogView.findViewById(R.id.btnOk);
		final Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
		
		LinearLayout footerview = (LinearLayout) getLayoutInflater().inflate(
				R.layout.add_group, null);
		groupList.addFooterView(footerview);
		groupList.setAdapter(adapter);
		groupList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				//新建组
				if(position == adapter.getCount()){
					dialog.setContentView(dialogView);
					dialog.show();
				}else if(position == 0){
					
				}else{
					if(groupPopupWindow.isShowing()){
						groupPopupWindow.dismiss();
					}
					groupPopupWindow.showAsDropDown(view, 182, -30);
					setGroupManger(groupPopupView, adapter, position);
					
					
				}
				
			}
		});
		//新建分组对话框中的按键监听
		btnOk.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				//TODO 新建组操作
				String groupName = ((EditText) dialog.findViewById(R.id.messageEdit)).getText().toString().trim();
				if(groupName != null && !groupName.equals("")){
					adapter.addView(groupName);
					dialog.dismiss();
				}else{
					Toast.makeText(mContext, "请输入分组名称", Toast.LENGTH_LONG).show();
				}
				
				
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				dialog.dismiss();
				
			}
		});

	}

	/**
	 * 设置分组管理按钮
	 * */
	private void setGroupManger(View popupView, final SimpleStrAdapter adapter, final int position){
		Button btnDelete = (Button) popupView.findViewById(R.id.btnDelete);
		Button btnReName = (Button) popupView.findViewById(R.id.btnReName);
		
		//删除分组
		btnDelete.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				groupPopupWindow.dismiss();
				final View dialogView = mInflater.inflate(R.layout.dlg_add_group, null);
				final EditText messageEdit = ((EditText) dialogView.findViewById(R.id.messageEdit));
				final TextView messageText = ((TextView) dialogView.findViewById(R.id.messageText));
				final TextView titleText = ((TextView) dialogView.findViewById(R.id.titleText));
				messageEdit.setVisibility(View.GONE);
				messageText.setText(getString(R.string.delete_group_msg, adapter.getItem(position)));
				titleText.setText(getString(R.string.delete_group_title));
				final Dialog deleteDialog = new Dialog(mContext, R.style.DialogStyle);
				deleteDialog.setContentView(dialogView);
				deleteDialog.show();
				WindowManager.LayoutParams params = deleteDialog.getWindow().getAttributes();
				params.width = DLG_DELETE_GROUP_WIDTH;
				params.height = DLG_DELETE_GROUP_HEIGHT;
				deleteDialog.getWindow().setAttributes(params);
				((Button) dialogView.findViewById(R.id.btnOk)).setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						adapter.removeView(position);
						deleteDialog.cancel();
						
					}
				});
				((Button) dialogView.findViewById(R.id.btnCancel)).setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						deleteDialog.cancel();
						
					}
				});
				
			}
		});
		//重命名分组
		btnReName.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				groupPopupWindow.dismiss();
				final View dialogView = mInflater.inflate(R.layout.dlg_add_group, null);
				final TextView messageText = (TextView) dialogView.findViewById(R.id.messageText);
				final EditText messageEdt = (EditText) dialogView.findViewById(R.id.messageEdit);
				messageEdt.setText((CharSequence) adapter.getItem(position));
				messageText.setText(getString(R.string.rename_group_msg));
				final Dialog renameDialog = new Dialog(mContext, R.style.DialogStyle);
				renameDialog.setContentView(dialogView);
				renameDialog.show();
				WindowManager.LayoutParams params = renameDialog.getWindow().getAttributes();
				params.width = DLG_EDIT_GROUP_WIDTH;
				params.height = DLG_EDIT_GROUP_HEIGHT;
				renameDialog.getWindow().setAttributes(params);
				((Button) dialogView.findViewById(R.id.btnOk)).setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						String newName = messageEdt.getText().toString().trim();
						if(newName != null && !newName.equals("")){
							adapter.relaceName(position, newName);
							renameDialog.cancel();
						}else{
							Toast.makeText(mContext, "分组名称不能为空", Toast.LENGTH_LONG).show();
						}
						
					}
				});
				((Button) dialogView.findViewById(R.id.btnCancel)).setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						renameDialog.cancel();
						
					}
				});
				
			}
		});
	}
	/**
	 * 显示更多下拉弹出框
	 * */
	private void showPopupWindow(int currentView) {
		if (morePopupWindow != null) {
			//通讯录好友标签下下拉按钮的视图
			LinearLayout commView = (LinearLayout) morePopupView.findViewById(R.id.commView);
			//云好友标签下下拉按钮的视图
			LinearLayout couldView = (LinearLayout) morePopupView.findViewById(R.id.couldView);
			if (currentView == 1) {
				if (!morePopupWindow.isShowing()) {
					morePopupWindow.showAsDropDown(btnMore, 0, 15);
					btnMore.setImageResource(R.drawable.more_fold);
					morePopupWindow
							.setOnDismissListener(new PopupWindow.OnDismissListener() {

								public void onDismiss() {
									btnMore.setImageResource(R.drawable.more_unfold);

								}
							});
				}
				
				Button btnFindFriends = (Button) morePopupView
						.findViewById(R.id.btnFindFriends);
				commView.setVisibility(View.GONE);
				couldView.setVisibility(View.VISIBLE);
				btnFindFriends.setOnClickListener(this);
				
			} else if (currentView == 2) {
				if (!morePopupWindow.isShowing()) {
					morePopupWindow.showAsDropDown(btnMore, 0, 15);
					btnMore.setImageResource(R.drawable.more_fold);
					morePopupWindow
							.setOnDismissListener(new PopupWindow.OnDismissListener() {

								public void onDismiss() {
									btnMore.setImageResource(R.drawable.more_unfold);

								}
							});
				}
				Button btnCreateNew = (Button) morePopupView
						.findViewById(R.id.btnCreateNew);
				Button btnImport = (Button) morePopupView
						.findViewById(R.id.btnImport);
				Button btnManage = (Button) morePopupView
						.findViewById(R.id.btnManage);
				couldView.setVisibility(View.GONE);
				commView.setVisibility(View.VISIBLE);
				btnCreateNew.setOnClickListener(this);
				btnImport.setOnClickListener(this);
				btnManage.setOnClickListener(this);
			}
		}
	}
	
	/**
	 * 设置搜索界面
	 * */
	private void setSearchView() {
		
		final LinearLayout fuzzyLayout = (LinearLayout) searchPopupView.findViewById(R.id.fuzzySearchLayout);
		final LinearLayout exactLayout = (LinearLayout) searchPopupView.findViewById(R.id.exactSearchLayout);
		final Button btnfuzzy = (Button) searchPopupView.findViewById(R.id.btnFuzzySearch);
		final Button btnexact = (Button) searchPopupView.findViewById(R.id.btnExactSearch);
		final EditText fuzzyInput = (EditText) searchPopupView.findViewById(R.id.fuuzzyEdtInput);
		final GridView resultGrid = (GridView) searchPopupView.findViewById(R.id.resultGrid);
		final TextView noResultHint = (TextView) searchPopupView.findViewById(R.id.noResultHint);
		
		((Button) searchPopupView.findViewById(R.id.btnBack))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						if(searchPopupWindow.isShowing()){
							searchPopupWindow.dismiss();
						}

					}
				});
		btnfuzzy.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						fuzzyLayout.setVisibility(View.VISIBLE);
						exactLayout.setVisibility(View.GONE);
						v.setBackgroundResource(R.drawable.btn_search_fuzzy_select);
						btnexact.setBackgroundResource(R.drawable.btn_search_exact_normal);
					}
				});
		btnexact.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						exactLayout.setVisibility(View.VISIBLE);
						fuzzyLayout.setVisibility(View.GONE);
						v.setBackgroundResource(R.drawable.btn_search_exact_select);
						btnfuzzy.setBackgroundResource(R.drawable.btn_search_fuzzy_normal);

					}
				});
		((Button) searchPopupView.findViewById(R.id.btnSmallSearch))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						String fuzzyKey = fuzzyInput.getText().toString().trim();
						if(!fuzzyKey.equals("")){
							noResultHint.setText(getString(R.string.search_no_result_1, fuzzyKey));
						}else{
							Toast.makeText(mContext, "请输入模糊搜索关键字", Toast.LENGTH_SHORT).show();
						}
					}
				});
		((Button) searchPopupView.findViewById(R.id.btnLargeSearch))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						// TODO Auto-generated method stub

					}
				});
		ArrayList<Contact> list = new ArrayList<Contact>();
		Contact info = new Contact();
		for(int i = 0; i<12; i++){
			list.add(info);
		}
		SearchResultAdapter adapter = new SearchResultAdapter(mContext, list);
		resultGrid.setAdapter(adapter);
	}
}
